package org.devf.fork.imsimulator.view;

import cn.hutool.core.util.StrUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.devf.fork.imsimulator.help.Md5Util;
import org.devf.fork.imsimulator.service.LoginService;
import org.devf.fork.imsimulator.service.ServiceFactory;
import org.devf.fork.imsimulator.service.TokenMgr;
import org.devf.fork.imsimulator.service.vo.LoginResponse;
import org.devf.fork.imsimulator.socket.DefaultTcpClient;
import org.devf.fork.imsimulator.socket.TcpClientFactory;
import org.devf.fork.imsimulator.socket.handler.MsgHandlerFactory;
import org.devf.fork.imsimulator.socket.handler.listener.ConnectResultListener;

import java.io.IOException;

public class LoginController extends BaseController implements ConnectResultListener {

    @FXML
    public TextField usernameField;
    @FXML
    public PasswordField passwordField;
    @FXML
    public Label tip;
    @FXML
    public TextField deviceField;


    @FXML
    private void initialize() {
        usernameField.setText("13640218134");
        passwordField.setText("123456");

        //注册消息监听器
        MsgHandlerFactory.ConnectHandler().register(this);
    }


    @FXML
    public void loginButtonClicked(ActionEvent actionEvent) {
        //登录
        if (StrUtil.isBlank(usernameField.getText())){
            tip.setText("账号不能为空！！");
            return;
        }
        if (StrUtil.isBlank(passwordField.getText())){
            tip.setText("密码不能为空！！");
            return;
        }
        if (StrUtil.isBlank(deviceField.getText())){
            tip.setText("设备号不能为空！！");
            return;
        }

        tip.setText("销毁存在的socket...");
        TcpClientFactory.getDefaultTcpClient().ifPresent(DefaultTcpClient::destroy);

        tip.setText("获取token...");
        LoginService loginService = ServiceFactory.getSingleLoginService();
        LoginResponse loginResponse = loginService.requestLogin(usernameField.getText(), Md5Util.md5(passwordField.getText()),deviceField.getText());
        if (null == loginResponse){
            tip.setText("调用http登录接口验证失败,请查看日志");
            return;
        }

        tip.setText("发起tcp连接...");
        String token = loginResponse.getToken();
        boolean isOk = loginService.buildTcpConnect(loginResponse.getUser(),token);
        if (isOk){
            TokenMgr.userModel = loginResponse.getUser();
            TokenMgr.token = loginResponse.getToken();
            TokenMgr.account = usernameField.getText();
            TokenMgr.password = passwordField.getText();
            TokenMgr.clientCode = deviceField.getText();
            tip.setText("已经发送connect，等待服务器响应！！");
        }
    }

    /**
     * connect 连接指令处理
     * @param obj packet包的data数据
     */
    @Override
    public void suc(Object obj) {
        System.out.println("和服务建立连接成功");
        refreshView(()->{
            try {
                toChatController();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Stage curStage = (Stage) usernameField.getScene().getRoot().getScene().getWindow();
            curStage.close();
        });
    }

    @Override
    public void fail(String errorMsg) {
        AlterHelp.alter(errorMsg);

        TokenMgr.userModel =null;
        TokenMgr.token =null;
        TokenMgr.account = null;
        TokenMgr.password = null;
        TokenMgr.clientCode = null;
        TcpClientFactory.getDefaultTcpClient().ifPresent(DefaultTcpClient::destroy);

    }


}